package springapp.web;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import springapp.service.ProfileResourceUtility;
import springapp.service.UserProfileForm;

@Controller
@SessionAttributes({ "command" })
@RequestMapping("/profile")
public class ProfileController {
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView showProfileForm() {

		return new ModelAndView("edituserprofile", "command",
				new UserProfileForm());
	}

	private ProfileResourceUtility resourceUtility;

	@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "image/jpeg")
	public @ResponseBody
	byte[] test() throws IOException {
		return getResourceAsByteArray(this.resourceUtility
				.getDummyProfileSmallPicture().getFile().getAbsolutePath());
	}

	/**
	 * Get the resource from jar-package as input stream to get the byte[] raw
	 * format
	 * 
	 * @param filePath
	 *            The local file name
	 * @return The image byte array
	 * @throws IOException
	 */
	private byte[] getResourceAsByteArray(String filePath) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream bais = null;
		try {
			bais = new FileInputStream(filePath);
			int c;
			while ((c = bais.read()) != -1) {
				baos.write(c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bais != null) {
				bais.close();
			}
			baos.close();
		}
		return baos.toByteArray();
	}

	public ProfileResourceUtility getResourceUtility() {
		return resourceUtility;
	}

	@Autowired
	public void setResourceUtility(ProfileResourceUtility resourceUtility) {
		this.resourceUtility = resourceUtility;
	}
}
